<?php
/**
 *上传接口
 */
namespace app\attach\controller;
use app\common\controller\Api;

class Upload extends Api {
	protected $uploadModel = '';
	protected $mod = '';
	protected $type_map = [
		//所有附件分类定义, '附件类型'=>['最大文件数','超过最大数自动更新保存信息']
		'stream' => [
			'max' => 0, //不限制
			'callback' => ['model', 'stream/Stream', 'updateIcon', ['stream_icon' => 'id', 'uid' => 'uid']],
		],
        'gift' => [
            'max' => 0,
        ],
        'stream_config_icon' =>[
            'max' => 1,
        ],
		'stream_3gconfig_app_logo' =>[
            'max' => 1,
        ],
		'file' => [
			'max' => 0,
		],
	];
	/**
	 * 初始化配置信息
	 * @var array
	 */
	protected $config = [
		// 允许上传的文件MiMe类型
		'mimes' => [],
		// 上传的文件大小限制 (0-不做限制)
		'maxSize' => 2,
		// 允许上传的文件后缀
		'exts' => ['jpg', 'jpeg', 'bmp', 'png'],
		// 自动子目录保存文件
		'autoSub' => true,
		// 子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
		'subName' => ['date', 'Y-m-d'], //
		//保存根路径
		'rootPath' => '',
		// 保存路径
		'savePath' => '',
		// 上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
		'saveName' => [], //'uniqid', ''
		// 文件保存后缀，空则使用原后缀
		'saveExt' => '',
		// 存在同名是否覆盖
		'replace' => true,
		// 是否生成hash编码
		'hash' => true,
		// 检测文件是否存在回调，如果存在返回文件信息数组
		'callback' => false,
		// 文件上传驱动e,
		'driver' => 'Local',
		// 上传驱动配置
		'driverConfig' => [],
		'thumb' => true,
		'thumb_list' => [
			't' => [36, 36],
			's' => [48, 48],
			'm' => [96, 96],
			'd' => [144, 144],
			'b' => [192, 192],
		],
	];
	public function __construct($config = []) {
		parent::__construct();
		parent::_initialize();
		//$this->config = array_merge($config);
		zbdefine('UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . '/public/uploads/');
		$this->config['rootPath'] = UPLOAD_PATH;
		$this->mod = model('attach/Attach');
		return $this;
	}
	/**
	 * @name 上传通用接口
	 */
	public function _empty($type) {
		//解析到处理方法
		$this->type = $type;
		return $this->handle();
	}
    /**
	 * @name 上传通用接口
	 */
	public function stream() {
		//解析到处理方法
		$this->type = 'stream';
		return $this->handle();
	}
    /**
	 * @name 上传通用接口
	 */
	public function file() {
		//解析到处理方法
		$this->type = 'file';
		return $this->handle();
	}
	/**
	 * @name 上传头像
	 */
	public function handle() {
		$st = self::checkApi();
		if (true !== $st) {
			return $this->api_info;
		}

		$type = $this->type;
		if (!$type || !array_key_exists(strtolower($type), $this->type_map)) {
			return getApiErrorCode('00404');
		}
		//$this->config['subName'] = ['strtolower',$type];//'date', 'Y-m-d'
		if ($type == 'file') {
			$this->config['maxSize'] = 20;
			$this->thumb = false;
			$this->config['exts'] = [];
		}
		$this->config['saveName'] = ['getFileName', ['filename' => '__FILE__', 'uid' => $this->uid]];
		/** 自定义生成缩略图 不够用的时候可以扩展**/
		if ($this->thumb === false || $this->thumb === 'false') {
			$this->config['thumb'] = false;
		} elseif ($this->thumb != '' && $this->thumb !== 'false') {
			$thumb_list = array_unique(explode(',', $this->thumb));
			if ($thumb_list) {
				foreach ($thumb_list as $k => $v) {
					if (count($this->config['thumb_list']) > 8) {
						break;
					}
					$reg = '/(\d+)[^\d]+(\d+)/';
					preg_match($reg, $v, $value);
					$this->config['thumb_list'] = array_merge($this->config['thumb_list'], [$value[1] . 'x' . $value[2] => [$value[1], $value[2]]]);
				}
			}
			unset($thumb_list);
			$this->config['thumb'] = true;
		}
		$this->uploadModel = new \org\Upload($this->config);
		$info = $this->uploadModel->upload();
		if (!$info) {
			$error = getApiErrorCode('40500');
			$error['message'] = $this->uploadModel->getError();
			return $error;
		} else {
			$data = [];
			foreach ($info as &$v) {
				$v['uid'] = $this->uid ?: 0;
				$v['mime_type'] = $v['type'];
				$v['type'] = $type;
				$attach_id = $this->mod->addAttach($v, $type, $this->type_map[$type]);
				$one = [
					'attach_id' => $attach_id,
					'attach_type' => $type,
					'urls' => (object) $this->mod->getAttachUrl($attach_id),
				];
				array_push($data, $one);
				unset($v);
			}
			return ['code' => '00000', 'data' => $data];
		}
	}

	public function uptest() {
		$GLOBALS['format'] = 'html';
		return $this->fetch();
	}

}